package com.pm.framework.web.service;


import com.pm.common.core.domain.entity.SysUser;
import com.pm.common.core.domain.model.LoginUser;
import com.pm.common.enums.UserStatus;
import com.pm.common.exception.ServiceException;
import com.pm.common.utils.MessageUtils;
import com.pm.common.utils.StringUtils;
import com.pm.system.domain.SysConfig;
import com.pm.system.mapper.SysConfigMapper;
import com.pm.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class SsoUserDetailsServiceImpl implements UserDetailsService {

        private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

        @Autowired
        private ISysUserService userService;

        @Autowired
        private SysPasswordService passwordService;

        @Autowired
        private SysPermissionService permissionService;

        @Resource
        SysConfigMapper sysConfigMapper;



        public UserDetails loadUserByUserNo(String userNo) throws UsernameNotFoundException
        {
            SysUser user = userService.selectUserByUserNo(userNo);



            //OA 单点登录的，无账号就用游客账号
            if (StringUtils.isNull(user))
            {
                SysConfig sysConfig = new SysConfig();
                sysConfig.setConfigKey("VISCODE_USER_NO");
                userNo = sysConfigMapper.selectConfig(sysConfig).getConfigValue() ;
                user = userService.selectUserByUserNo(userNo);
            }
             if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
            {
                log.info("登录用户：{} 已被删除.", userNo);
                throw new ServiceException(MessageUtils.message("user.password.delete"));
            }
            else if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
            {
                log.info("登录用户：{} 已被停用.", userNo);
                throw new ServiceException(MessageUtils.message("user.blocked"));
            }
            return createLoginUser(user);
        }

        public UserDetails createLoginUser(SysUser user)
        {
            return new LoginUser(user.getUserId(), user.getDeptId(), user, permissionService.getMenuPermission(user));
        }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        return null;
    }
}

